<?php
function lastfm_api_class($class){
	$authVars['apiKey'] = '260520b01384df97f2e69288bf4258d3';
	$auth = new lastfmApiAuth('setsession', $authVars);
	$apiClass = new lastfmApi();
	return  $apiClass->getPackage($auth, $class);
}

function library_cache_artists($user, $page = 1, $limit = 50, $batch_size = 1){

	if($artist_results = _library_cache_artists($user, $page, $limit)){
		$pages = $artist_results['totalPages'];
		$initials_found = $artist_results['initials_found'];
		if($batch_size > 1){
			for($i=$page+1;$i<=$pages && $i < $page+$batch_size;$i++){
				if(!$artist_further_results = _library_cache_artists($user,$i, $limit)){
					break;
				}
				$initials_found = array_merge($initials_found,$artist_further_results['initials_found']);

			}
		}
		library_update_artists($user,$page,$batch_size);
		$user->total_pages = $pages;
		$user->current_page = $page + $batch_size-1;
		if($user->current_page <= $user->total_pages){
			$user->last_refreshed = date ("Y-m-d H:i:s");
		}
		$user->save();


		//cache a few tags, but not too many that the call slows down
		library_cache_tags($user,10);

		return array('pages' => $pages,'initials_found' => $initials_found);
	}else{
		return 0;
	}
}


function _library_cache_artists($user, $page = 1, $limit = 50){
	$libraryClass = lastfm_api_class('library');
	$methodVars = array(
		'user' => $user->username,
		'page' => $page,
	);
	if($limit < 50){
		$methodVars['limit'] = $limit;
	}
	if($library = $libraryClass->getArtists($methodVars)){
		$initials_found = array();
		$values = array();
		foreach($library['results'] as $i => $artist){
			$letters = str_split($artist['name']);
			$initial = strtoupper($letters[0]);
			if($initial == 'T' && stristr($artist['name'],'the ') == 0 && count($letters) > 4){
				$initial = strtoupper($letters[4]);
			}
			if(!in_array($initial,$initials_found)){
				$initials_found[]=$initial;
			}
			$values[] = "('".mysql_escape_string($user->current_cache_guid)."'"
			.",".mysql_escape_string($page)
			.",'".mysql_escape_string($artist['mbid'])."'"
			.",'".mysql_escape_string($artist['name'])."'"
			.",'".mysql_escape_string($initial)."'"
			.",".mysql_escape_string($artist['playcount'])
			.",".mysql_escape_string($user->id).")";

		}
		//DELAYED?
		$sql = "INSERT INTO library_cache VALUES ".implode(",",$values);
		mysql_query($sql);
		$library['initials_found'] = $initials_found;
		return $library;
	} else{
		return false;
	}

}
function library_artists($user, $initial = false){
	$sql = "SELECT a.*,ua.playcount
	FROM artist a 
		INNER JOIN user_artist ua 
			ON a.id = ua.artist_id
		INNER JOIN user u
			ON u.id = ua.user_id
	WHERE u.username = '%s' ";
	$args = array($user);
	if($initial){
		if(strlen($initial) == 1){
			$sql .= " AND a.initial = '%s'";
			$args[] = $initial;
		} else if(is_numeric($initial[0])){
			$sql .= " AND a.initial >='0' AND a.initial <='9' ";
		} else {
			$sql .= " AND (a.initial < '0' OR (a.initial > '9' AND a.initial < 'A') OR (a.initial > 'Z' AND a.initial < 'a') OR a.initial > 'z') ";
		}
	}
	//$sql .= 'ORDER BY name ASC ';
	$artists = array();
	if($result = db_query($sql,$args)){
		while($row = mysql_fetch_assoc($result)){
			$artists[] = array('name'=>$row['name'],'id'=>$row['id']);

		}
	}
	usort($artists,'compare_without_the');
	return $artists;

}

function library_albums($user, $artist_id){

	if($result = db_query('SELECT id, name, spotify_artist,spotify_expiry FROM artist WHERE id = %d',$artist_id)){
		$row = mysql_fetch_assoc($result);
		$artist = $row['name'];
		$libraryClass = lastfm_api_class('library');
		$methodVars = array(
		'user' => $user,
		'artist' => $artist,
		);

		$albums = $libraryClass->getAlbums($methodVars);
		if(array_key_exists('results',$albums)){
			$results = $albums['results'];

			$spotify_albums = spotify_albums_by_artist($artist,$row['id'],$row['spotify_artist'],$row['spotify_expiry']);

			foreach($results as $i => $album){
				foreach($spotify_albums as $j => $spotify_album){
					if(strtolower($album['name']) == strtolower($spotify_album['name'])){
						$results[$i]['spotify_id'] = $spotify_album['id'];
						break;
					}
				}

			}

			return $results;
		}

	}
	return false;
}

function library_update_artists($user,$batch,$batch_size){
	$from = $batch;
	$to = $batch + $batch_size-1;

	//stopped worrying about cache guid, batches and users
	//just doing everyone at once where an update or insert looks to be needed

	db_query("INSERT INTO artist(mbid,name,initial)
SELECT lc.mbid,lc.artist,lc.initial
FROM `library_cache` lc
LEFT JOIN artist a
ON lc.artist = a.name
WHERE a.name IS NULL");
	//AND cache_guid = '%s' AND batch>= %d AND batch <= %d",$user->current_cache_guid,$from,$to);

	db_query("INSERT INTO user_artist(artist_id, user_id,playcount)
SELECT a.id, lc.user_id, MAX(lc.playcount)
FROM library_cache lc
INNER JOIN artist a ON a.name = lc.artist
LEFT OUTER JOIN user_artist ua ON a.id = ua.artist_id AND lc.user_id = ua.user_id
WHERE ua.artist_id IS NULL
GROUP BY a.id, lc.user_id");

	//AND cache_guid = '%s'
	//AND batch>= %d AND batch <= %d",$user->user_id,$user->current_cache_guid,$from,$to);
	//



	db_query("UPDATE user_artist ua
		INNER JOIN artist a ON ua.artist_id = a.id
		INNER JOIN library_cache lc ON a.name = lc.artist AND lc.user_id = ua.user_id
	SET ua.playcount = lc.playcount
	WHERE ua.playcount < lc.playcount");
	//	WHERE lc.user_id = %d
	//	AND cache_guid = '%s'
	//	AND batch>= %d AND batch <= %d",$user->id,$user->current_cache_guid,$from,$to);

	db_query("DELETE FROM library_cache lc
USING library_cache lc
INNER JOIN artist a ON a.name = lc.artist
INNER JOIN user_artist ua ON a.id = ua.artist_id AND ua.playcount>=lc.playcount
AND lc.user_id = ua.user_id");
}

function library_cache_tags($user, $batch_size = 10){
	//find user's most popular artists that have no tags
	$sql = "SELECT a.id AS artist_id, a.name
			FROM artist a 
					LEFT JOIN artist_genre ag 
						ON a.id = ag.artist_id
					INNER JOIN user_artist ua
						ON ua.artist_id = a.id
			WHERE ag.tag IS NULL AND ua.user_id =%d
			GROUP BY a.id, a.name
			ORDER BY ua.playcount DESC
			LIMIT %d";

	if($result = db_query($sql,array($user->id, $batch_size))){
		$artistClass = lastfm_api_class('artist');
		$values = array();
		while($artist_row = mysql_fetch_assoc($result)){

			$methodVars = array(
				'artist' => $artist_row['name'],
			);

			if($artist_results = $artistClass->getInfo($methodVars)){
				if(is_array($artist_results['tags'])){
					foreach($artist_results['tags'] as $tag){
						$values[] = "(".$artist_row['artist_id'].",'".mysql_escape_string($tag['name'])."')";
					}
				}
			}

		}
		if(count($values) > 0){
			$sql = "REPLACE INTO artist_genre(artist_id, tag) VALUES ".implode(",",$values);
			
			db_query($sql);
			return true;
		}

	}
	return false;
}



function compare_without_the($a, $b){
	//	if(strlen($a) > 4 && stripos($a,'the') == 0){
	//		$a = substr($a, 4);
	//	}
	//	if(strlen($a) > 4 && stripos($b,'the') == 0){
	//		$b = substr($b, 4);
	//	}
	return strcasecmp($a['name'],$b['name']);
}


function compare_name($a, $b)
{

	return strcasecmp($a['name'],$b['name']);
}